package cn.dinxian.activiti.demo2.controller;

import cn.dinxian.activiti.demo2.service.MyTaskUtil;
import cn.dinxian.activiti.demo2.tool.PageUtils;
import cn.dinxian.activiti.entity.ActivitiTask;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import cn.dinxian.entity.ActTaskDTO;
import cn.dinxian.entity.BaseDTO;
import cn.dinxian.entity.CommonResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.FormProperty;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;

import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author dingxian
 * @Title:
 * @param:
 * @return:
 * @Date 2023/2/27 20:42
 * @Description:
 */
@RestController
@RequestMapping("TaskService-provider")
@Slf4j
@Service
public class MyTaskController {
  @Autowired
  TaskService taskService;
  
  @Autowired
  RepositoryService repositoryService;

  @Autowired
  MyTaskUtil myTaskUtil;

  /**
   *  查询当前流程的任务所有任务
   * @param processDefinitionKey
   * @return
   */
  @PostMapping("/TaskQueryByKey")
  public CommonResult<Object> taskQueryByKey(String processDefinitionKey ){

    final List<Task> list = taskService.createTaskQuery()
        .processDefinitionKey(processDefinitionKey).list();
    final List<ActivitiTask> activitiTasks =new ArrayList<>() ;

    for (Task task : list) {
      ActivitiTask  activitiTask=new ActivitiTask();
      activitiTask.setCreatedDate(task.getCreateTime());
      activitiTask.setId(task.getId());
      activitiTask.setName(task.getName());
      activitiTasks.add(activitiTask);
    }
    return new CommonResult<Object>(200,null,activitiTasks);
  }

  @PostMapping( "/tasks")
  public CommonResult<List<ActTaskDTO>> tasks(@RequestBody ActTaskDTO dto){
    //构建query
    final TaskQuery taskQuery = this.buildTaskQuer(dto);

    taskQuery.or().taskCandidateOrAssigned(dto.getUserId(),dto.getGroupList()).taskOwner(dto.getUserId())
        .endOr();
    //查询
    IPage page = PageUtils.getPage(taskQuery, dto);
    //解码
    List<ActTaskDTO>  list = myTaskUtil.assembleTask(page.getRecords());
    return new CommonResult<List<ActTaskDTO>>(200,null,list); 
  }
  

  /**
   *     完成当前的任务 
   * @param param 
   *   id 任务id
   *   map1 -> variables 加入的变量
   * @return
   */
  @PostMapping("/complete")
  public CommonResult<Object> complete(@RequestBody BaseDTO param) {
    final String taskId = param.getId();
    final Map<String, Object> variables = param.getMap_1();
    try {
      if(variables!=null){
        taskService.complete(taskId,variables);
      }
      else {
        taskService.complete(taskId);
      }
    }catch (Exception e){
      return new CommonResult<Object>(500,"完成实例的时候失败",e.getMessage()); 
    }
     return new CommonResult<Object>(200,"完成");
  }


  @PostMapping( "/getUserTaskForm")
  public CommonResult<ActTaskDTO> getUserTaskForm(@RequestBody ActTaskDTO dto){
    final Task task = this.buildTaskQuer(dto).list().get(0);
/*  ------------------------------------------------------------------------------
            FormProperty_0ueitp2--__!!类型--__!!名称--__!!是否参数--__!!默认值
            例子：
            FormProperty_0lovri0--__!!string--__!!姓名--__!!f--__!!同意!!__--驳回
            FormProperty_1iu6onu--__!!int--__!!年龄--__!!s

            默认值：无、字符常量、FormProperty_开头定义过的控件ID
            是否参数：f为不是参数，s是字符，t是时间(不需要int，因为这里int等价于string)
            注：类型是可以获取到的，但是为了统一配置原则，都配置到
            */

    //注意!!!!!!!!:表单Key必须要任务编号一模一样，因为参数需要任务key，但是无法获取，只能获取表单key“task.getFormKey()”当做任务key
    UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
        .getFlowElement(task.getFormKey());

    if (userTask == null) {
      return null;
    }
    List<FormProperty> formProperties = userTask.getFormProperties();
    List<String> collect = formProperties.stream().map(fp -> fp.getId()).collect(Collectors.toList());
    
     return new CommonResult<ActTaskDTO>(200,null, ActTaskDTO.builder().listParam(collect).build());
  }
  
  public TaskQuery buildTaskQuer(ActTaskDTO request){ 
    TaskQuery taskQuery = this.taskService.createTaskQuery();
    //if (ObjectUtils.isNotEmpty(request.getUserId())) {
    //  taskQuery.taskAssignee(request.getUserId());
    //}
    //taskQuery.or().taskCandidateOrAssigned(request.getUserId(),null);

    if (ObjectUtils.isNotEmpty(request.getRoleId())) {
      taskQuery.taskCandidateGroup(request.getRoleId());
    }
    if (ObjectUtils.isNotEmpty(request.getId())) {
      taskQuery.taskId(request.getId());
    }
    if (ObjectUtils.isNotEmpty(request.getTaskId())) {
      taskQuery.taskId(request.getTaskId());
    }
    if (ObjectUtils.isNotEmpty(request.getProcessInstanceId())) {
      taskQuery.processInstanceId(request.getProcessInstanceId());
    }
    return taskQuery;
  }


  
  
}
